//
//  PlayerViewController.m
//  网络FM
//
//  Created by dlios on 15/5/25.
//  Copyright (c) 2015年 dengzhicheng.com. All rights reserved.
//

#import "PlayerViewController.h"
#import  <AudioStreamer.h>
#import "Player.h"

#import <UIImageView+WebCache.h>

#import <MediaPlayer/MediaPlayer.h>

#import "CellectDB.h"
#import "CellectDatabase.h"
#import "CellectModel.h"
#import <KVNProgress.h>

#import <AVFoundation/AVFoundation.h>

#import "WeiboSDK.h"
#import "AppDelegate.h"
#define kRedirectURI    @"http://www.sina.com"

@interface PlayerViewController ()
@property (strong,nonatomic)MPMoviePlayerController *streamPlayer;

@end

@implementation PlayerViewController




- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}
- (void)dealloc
{
    [_playerView release];
    [_urlForPlay release];
    [_picURL release];
    [_collect release];
    [super dealloc];
}

- (void)loadView
{
    [super loadView];
    [self createPlayView];
    [self beginToPlay];
//    AVAudioSession *session = [AVAudioSession sharedInstance];
//    [session setActive:YES error:nil];
//    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
//    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];

}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    UIImage *image = [UIImage imageNamed:@"play_bg.png"];
    self.view.layer.contents = (id)image.CGImage;
    self.view.layer.backgroundColor = [UIColor clearColor].CGColor ;
}

//+ (void)initialize
//{
//    // 后台播放，第三步，设置 音频会话类型
//    AVAudioSession *session = [AVAudioSession sharedInstance];
//    // 类型是:播放和录音
//    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
//    // 而且要激活 音频会话
//    [session setActive:YES error:nil];
//}

- (void)createPlayView
{
    
    
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    
    //创建播放界面中间的view
    UIImageView *bg_view = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width - 80, width - 80)];
    [bg_view setCenter:CGPointMake(width / 2, height / 2 - 80)];
    [self.view addSubview:bg_view];
    [bg_view  setImage:[UIImage imageNamed:@"play_playbg.png"]];
    [bg_view release];
    
    
    //创建承载图片的imageview
    UIImageView *show_view = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 220.0f / 295.0f * (width - 80),  220.0f / 295.0f * (width - 80))];
    [show_view setCenter:CGPointMake(width / 2,height / 2 - 80)];
     [show_view setBackgroundColor:[UIColor clearColor]];
     [show_view sd_setImageWithURL:[NSURL URLWithString:self.picURL] placeholderImage:[UIImage imageNamed:nil] options:SDWebImageRetryFailed];
    [self.view addSubview:show_view];
    [show_view release];

    
    
    
    //滚动title
    _FMname =  [[UILabel alloc]initWithFrame:CGRectMake(0, 0, width - 80, 60)];
    [_FMname setCenter:CGPointMake(width / 2,(width + height ) / 2 - 90 )];
    [self.view addSubview:_FMname];
    [self.FMname setTextColor:[UIColor whiteColor]];
    [self.FMname setFont:[UIFont systemFontOfSize:16]];
         [self.FMname setTextAlignment:NSTextAlignmentCenter];
    _FMname.text = self.tit;
    [_FMname release];
    
    

    
    
//    //创建进度条
    
    
    //左右轨图片
    UIImage *stetchLeftTrack= [UIImage imageNamed:@"brightness_bar.png"];
    UIImage *stetchRightTrack = [UIImage imageNamed:@"brightness_bar.png"];
    
    //滑块图片
    UIImage *thumbImage = [UIImage imageNamed:@"mark.png"];
    

    self.progressSlider = [[UISlider alloc]initWithFrame:CGRectMake(0, 0, width - 80, 20)];
    [self.progressSlider setCenter:CGPointMake(width / 2,  (width + height) / 2 - 50)];
    
    
    [self.progressSlider setBackgroundColor:[UIColor clearColor]];
 
    [self.progressSlider setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
    [self.progressSlider setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
    //防止高亮使用默认控件
    [self.progressSlider setThumbImage:thumbImage forState:UIControlStateHighlighted];
    [self.progressSlider setThumbImage:thumbImage forState:UIControlStateNormal];
    
    
    //滑块拖动时的事件
    [self.progressSlider addTarget:self action:@selector(changeProgress:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.progressSlider];
    //self.progressSlider.continuous = YES;

    
    
    //时间lable
    _lefttime = [[UILabel alloc]initWithFrame:CGRectMake(40, ((width + height) / 2 - 40), 40, 20)];
    [self.view addSubview:_lefttime];
    [_lefttime setTextColor:[UIColor whiteColor]];
    [_lefttime setFont:[UIFont systemFontOfSize:12]];
    [_lefttime release];
    
    _righttime = [[UILabel alloc]initWithFrame:CGRectMake(width - 85, ((width + height) / 2 - 40),50, 20)];
    [self.view addSubview:_righttime];
    [_righttime setTextColor:[UIColor whiteColor]];
    [_righttime setFont:[UIFont systemFontOfSize:12]];
    [_righttime release];

    //创建控制按钮
    _control = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [_control setCenter:CGPointMake(width / 2, (width + height) / 2 + 20)];
    [_control setBackgroundImage:[UIImage imageNamed:@"play_pause.png"] forState:UIControlStateNormal];
    [_control addTarget:self action:@selector(controlAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_control];
    [_control release];
    
    CellectModel *model1 = [CellectDatabase selectWithTitle:self.tit];
    if (![self.tit isEqualToString:model1.titleName]) {
        //创建收藏按钮
        [self judgeCollectWithpicName:@"play_collect.png"];
        
        
    } else {
        //创建收藏按钮
        [self judgeCollectWithpicName:@"play_didcollect.png"];
    }
    
    
    // 分享按钮
    UIButton *shareButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [shareButton setCenter:CGPointMake(self.view.frame.size.width - 100, 50)];
    [shareButton setBackgroundColor:[UIColor clearColor]];
    [shareButton setImage:[UIImage imageNamed:@"fenxianganniu.png"] forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(shareButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareButton];
    [shareButton release];
    
    
    //创建返回列表按钮
    UIButton *back = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [back setCenter:CGPointMake(width / 2 - (width - 80) / 2, 50)];
    [back setBackgroundImage:[UIImage imageNamed:@"play_list.png"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:back];
    [back release];
    
   
    

    
    //快退
    UIButton *left = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 70)];
    [left setCenter:CGPointMake(width / 2 - 50 - 10 - 35, (width + height) / 2 + 20)];
    [left setBackgroundImage:[UIImage imageNamed:@"play_last.png"] forState:UIControlStateNormal];

    [left addTarget:self action:@selector(fastBack:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:left];
    [left release];
    
    //快进
    UIButton *right = [[UIButton alloc]initWithFrame:CGRectMake(0,0,70,70)];
    [right setCenter:CGPointMake(width / 2 + 50 + 10 + 35 ,  (width + height ) / 2 + 20)];
    [right setBackgroundImage:[UIImage imageNamed:@"play_next.png"] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(fastForward:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:right];
    [right release];
}

- (void)shareButtonPressed
{
    // 读取本地登录状态
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *str = [defaults objectForKey:@"loginState"];
    
    if ([str isEqual:@"0"]) {
        [KVNProgress showErrorWithStatus:@"请登录"];
    } else
    {
        
        AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
        
        WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
        authRequest.redirectURI = kRedirectURI;
        authRequest.scope = @"all";
        
        WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:myDelegate.wbtoken];
        request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                             @"Other_Info_1": [NSNumber numberWithInt:123],
                             @"Other_Info_2": @[@"obj1", @"obj2"],
                             @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
        //    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
        [WeiboSDK sendRequest:request];
    }
    
    
}

- (WBMessageObject *)messageToShare
{
    WBMessageObject *message = [WBMessageObject message];
    message.text = [NSString stringWithFormat:@"%@\n%@\n", self.tit, self.urlForPlay];
    
    return message;
}


//判断是否收藏
- (void)judgeCollectWithpicName:(NSString *)picName
{
    float width = self.view.frame.size.width;
    
    self.collect = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [_collect setCenter:CGPointMake(width - 40, 50)];
    [_collect setBackgroundImage:[UIImage imageNamed:picName] forState:UIControlStateNormal];
    [_collect addTarget:self action:@selector(collectAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_collect];
    [_collect release];
}


//快退按钮点击事件
- (void)fastBack:(id)sender
{     Player *play  = [Player playManager];
    if ((self.progressSlider.value > 0.05)) {
        play.streamer.currentPlaybackTime = (self.progressSlider.value - 0.05) * play.streamer.duration;
    }
  
}



//快进按钮点击事件
- (void)fastForward:(id)sender
{     Player *play  = [Player playManager];
   play.streamer.currentPlaybackTime = (self.progressSlider.value + 0.05) * play.streamer.duration;
}



//改变进度
- (void)changeProgress:(id)sender
{     Player *play  = [Player playManager];
    play.streamer.currentPlaybackTime = self.progressSlider.value * play.streamer.duration;
}



//收藏按钮点击事件
- (void)collectAction:(id)sender
{
    CellectModel *model1 = [CellectDatabase selectWithTitle:self.tit];
    CellectModel *model = [[CellectModel alloc] init];
    if (![self.tit isEqualToString:model1.titleName]) {
        model.titleName = self.tit;
        model.imageName = self.picURL;
        model.videoUrl = self.urlForPlay;
        model.people = self.speaker;
        [CellectDatabase insertWithModel:model];
        [KVNProgress showSuccessWithStatus:@"收藏成功"];
        [_collect setBackgroundImage:[UIImage imageNamed:@"play_didcollect.png"] forState:UIControlStateNormal];

    } else {
 
        [KVNProgress showErrorWithStatus:@"已收藏"];
    }

    
}





//收藏
- (void)updateProgress
{
    dispatch_main_after(2.0f, ^{
        [KVNProgress updateProgress:0.3f
                           animated:YES];
    });
    dispatch_main_after(2.5f, ^{
        [KVNProgress updateProgress:0.5f
                           animated:YES];
    });
    dispatch_main_after(2.8f, ^{
        [KVNProgress updateProgress:0.6f
                           animated:YES];
    });
    dispatch_main_after(3.7f, ^{
        [KVNProgress updateProgress:0.93f
                           animated:YES];
    });
    dispatch_main_after(5.0f, ^{
        [KVNProgress updateProgress:1.0f
                           animated:YES];
    });
}
static void dispatch_main_after(NSTimeInterval delay, void (^block)(void))
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        block();
    });
}



//播放按钮点击事件


- (void)controlAction:(id)sender
{

    Player *play  = [Player playManager];
    if (play.streamer.playbackState ==  MPMoviePlaybackStatePlaying) {
        [play.streamer pause];
        [_control setBackgroundImage:[UIImage imageNamed:@"play_on.png"] forState:UIControlStateNormal];

    }
    else
    {
        [play.streamer play];
         [_control setBackgroundImage:[UIImage imageNamed:@"play_pause.png"] forState:UIControlStateNormal];
  
    }
}

//定时器方法
- (void)timeConnect:(id)sender
{
    
        Player *play  = [Player playManager];
    
    NSInteger leftTime = play.streamer.currentPlaybackTime;
    NSInteger rightTime =play.streamer.duration;
    if (leftTime > rightTime) {
        [self.righttime setText:@"00 : 00"];
        [self.lefttime setText:@"00 : 00"];
        return ;
    }
    if (rightTime < 0) {
        [self.righttime setText:@"00 : 00"];
    }
    if (leftTime < 0) {
        [self.lefttime setText:@"00 : 00"];
        
    } else {
 
        NSString *le= [NSString stringWithFormat:@"%ld%ld : %ld%ld",(long)leftTime / 60 / 10,(long)leftTime / 60 % 10,(long)leftTime % 60 / 10,(long)leftTime % 60 % 10];
        [_lefttime setText:le];
        NSString *ri= [NSString stringWithFormat:@"%ld%ld : %ld%ld",(long)rightTime / 60 / 10,(long)rightTime / 60 % 10,(long)rightTime % 60 / 10,(long)rightTime % 60 % 10];
        [_righttime setText:ri];
        [self.progressSlider setValue:play.streamer.currentPlaybackTime/play.streamer.duration];
    }
  
}



- (void)beginToPlay
{
    [self.timer invalidate];
    self.timer = nil;
//        NSURL *streamUrl = [NSURL URLWithString:self.urlForPlay];
//        self.streamPlayer = [[MPMoviePlayerController alloc]initWithContentURL:streamUrl];
//        self.streamPlayer.controlStyle = MPMovieControlStyleEmbedded;
//        [self.streamPlayer play];
    

    Player *player = [Player playManager];
    NSURL *streamUrl = [NSURL URLWithString:self.urlForPlay];
    [player playWithUrl:streamUrl];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeConnect:) userInfo:nil repeats:YES];

}


//返回按钮事件
- (void)backAction:(id)sender
{
    
        [self.navigationController popViewControllerAnimated:YES];
    self.navigationController.navigationBarHidden = NO;
    Player *play  = [Player playManager];
    if (play.streamer.playbackState ==  MPMoviePlaybackStatePlaying) {
        UIView *controlView = [self.view.window.subviews objectAtIndex:1];
        UIImageView *imageView = [controlView.subviews objectAtIndex:0];
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.picURL] placeholderImage:[UIImage imageNamed:nil] options:SDWebImageRetryFailed];
        
        UILabel *lable = [controlView.subviews objectAtIndex:1];
        lable.text = self.tit;
        [controlView setAlpha:1];
    }    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
